package tc.maas.bulkfilerenamer.domain.filemanagement;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import tc.maas.bulkfilerenamer.domain.dataobjects.Directory;
import tc.maas.bulkfilerenamer.domain.filemanagement.interfaces.Containable;
import tc.maas.bulkfilerenamer.domain.filemanagement.interfaces.Container;
import tc.maas.bulkfilerenamer.domain.filemanagement.interfaces.FileSystemReader;

public class ContainerReader implements FileSystemReader {

    private Container container;
    private List<Containable> containables;

    public ContainerReader() {
    }

    public ContainerReader(final File file) {
        readContainer(file.getAbsolutePath());
    }

    public ContainerReader(final String path) {
        readContainer(path);
    }

    @Override
    public List<Containable> getContainables() {
        return containables;
    }

    @Override
    public Container getContainer() {
        return container;
    }

    @Override
    public void readContainer(final String path) {
        File file = new File(path);
        readContainer(file);
    }

    @Override
    public void readContainer(final File file) {
        if (file.isDirectory()) {
            container = new Directory(file);
            extractContainables(file);
        } else if (file.isFile()) {
            // TODO throw proper exception
        }
    }

    private void extractContainables(final File directory) {
        List<File> files = new ArrayList<File>();
        Collections.addAll(files, directory.listFiles());
        for (File file : files) {
            if (file.isFile()) {
                Containable containable = new tc.maas.bulkfilerenamer.domain.dataobjects.File(file);
                containables.add(containable);
            }
        }

    }

    @Override
    public Container updateContainer() {
        container.update();
        return container;
    }

    @Override
    public Container updateContainer(final Container container) {
        if (this.container == null) {
            this.container = container;
        }
        return container;
    }

}
